import java.util.HashMap;
import java.util.Map.Entry;


public class VectorTimeStamp extends TimeStamp {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private HashMap<String, Integer> time;
	
	public VectorTimeStamp(HashMap<String, Node> nodes, String local_name) {
		this.local_name = local_name;
		
		time = new HashMap<String, Integer>();
		for(Entry<String, Node> e: nodes.entrySet()){
			String name = e.getKey();
			time.put(name, 0);
		}
	}
	@Override
	public void increase() {
		time.put(local_name, time.get(local_name) + 1);
		//System.out.println("increase: " +time);
	}
	public HashMap<String, Integer> getTime() {
		return time;
	}
	public void setTime(HashMap<String, Integer> time) {
		this.time = time;
	}
	@Override
	public void show() {
		System.out.println(time);
	}
	@Override
	public void update(TimeStamp timeStamp) {
		HashMap<String, Integer> t = ((VectorTimeStamp)timeStamp).getTime();
		for(Entry<String, Integer> e: t.entrySet()){
			String name = e.getKey();
			int max = Math.max(e.getValue(), time.get(name));
			time.put(name, max);
		}
	}
	@Override
	public int compareTo(TimeStamp o) {
		VectorTimeStamp vts = (VectorTimeStamp)o;
		boolean equal = isEqual(time, vts.getTime());
		//boolean lessOrEqual = isLessOrEqual(time, vts.getTime());
		if(!equal){
			if(isLessOrEqual(time, vts.getTime())){
				return -1;
			}else if(isLessOrEqual(vts.getTime(), time)){
				return 1;
			}else{
				return 0;
			}
		}else { 
			return 0;
		}
	}
	private boolean isEqual(HashMap<String, Integer> time1,
			HashMap<String, Integer> time2) {
		for(Entry<String, Integer> e: time1.entrySet()){
			String name = e.getKey();
			if(e.getValue() != time2.get(name))
				return false;
		}
		return true;
	}
	private boolean isLessOrEqual(HashMap<String, Integer> time1,
			HashMap<String, Integer> time2) {
		for(Entry<String, Integer> e: time1.entrySet()){
			String name = e.getKey();
			if(e.getValue() > time2.get(name))
				return false;
		}
		return true;
	}
	
	@Override
	public String toString() {
		return time.toString();
	}

}
